/*
 * Created Ibrayev Y.A. - 19.12.2012
 */
package org.erps;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import javax.swing.JFileChooser;
import javax.swing.JList;

import org.compiere.apps.ADialog;
import org.compiere.model.I_FI_PPC;
import org.compiere.model.MBPBankAccount;
import org.compiere.model.MBPartner;
import org.compiere.model.MBank;
import org.compiere.model.MBankAccount;
import org.compiere.model.MFI_C_PaymentLine;
import org.compiere.model.MOrg;
import org.compiere.model.MPayment;
import org.compiere.model.Mhrmidcard;
import org.compiere.model.Mhrmintercheckoff;
import org.compiere.model.Mhrmintercheckoffline;
import org.compiere.model.Mhrmpayment;
import org.compiere.model.Mhrmpaymentlist;
import org.compiere.model.X_FI_PPC;
import org.compiere.model.X_hrm_idcard;
import org.compiere.sqlj.Payment;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.eevolution.model.X_HR_Employee;

public class MakeSwift {
	protected transient CLogger log = CLogger.getCLogger(getClass());
	protected static String endl = "\r\n";
	protected static String cMainHead = "1";
	protected static String cAppHead = "2";
	protected static String cText = "4";
	protected static String cSign = "5";

	protected static int WindowNo = -1;

	protected String SWIFTFileName = null;
	protected FileOutputStream fos = null;
	protected OutputStreamWriter out = null;
	protected int C_Payment_ID = -1;

	private MPayment payment = null;

	protected List<String> SWIFT = null;
	protected int AD_Org_ID = -1;
	protected int AD_Client_ID = -1;
	protected Properties ctx = null;
	protected StringBuffer emptyLA = new StringBuffer("");

	private Mhrmpayment m_hrmpayment = null;

	protected List<Item> Items = null;

	private int FI_ChiefSignature_ID = -1;
	private int FI_ChiefAccountantSignature_ID = -1;
	private String BPAccountCode = null;
	private int C_BPartner_ID = -1;
	private Timestamp DateTrx = null;
	private BigDecimal PayAmt = new BigDecimal(0);
	private String Description = "";
	private int C_BankAccount_ID = -1;
	private int C_BP_BankAccount_ID = -1;
	private int FI_PPC_ID = -1;
	private String DocumentNo = "";
	
	private Mhrmintercheckoff m_hrmintercheckoff = null;

	public MakeSwift(Properties ctx, Mhrmpayment hrmpayment) {
		super();
		this.ctx = ctx;
		m_hrmpayment = hrmpayment;
		AD_Client_ID = getAD_Client_ID(ctx);
		AD_Org_ID = getAD_Org_ID(ctx);
		InitForHrmpayment(m_hrmpayment);
	}

	public MakeSwift(Properties ctx, Mhrmintercheckoff hrmintercheckoff) {
		super();
		this.ctx = ctx;
		m_hrmintercheckoff = hrmintercheckoff;
		AD_Client_ID = getAD_Client_ID(ctx);
		AD_Org_ID = getAD_Org_ID(ctx);
		InitForHrmintercheckoff(m_hrmintercheckoff);
	}
	
	public MakeSwift(Properties ctx, int WindowNo) {
		this.WindowNo = WindowNo;
		this.ctx = ctx;
		C_Payment_ID = getC_Payment_ID(ctx);
		MPayment Payment = new MPayment(ctx, C_Payment_ID, null);
		InitForPayment(Payment);
	}

	public MakeSwift(Properties ctx, int WindowNo, int PaymentID) {
		this.WindowNo = WindowNo;
		this.ctx = ctx;
		C_Payment_ID = getC_Payment_ID(ctx);
		MPayment Payment = new MPayment(ctx, C_Payment_ID, null);
		InitForPayment(Payment);
		payment = new MPayment(ctx, PaymentID, null);
	}
	
	
	public MakeSwift(Properties ctx, MPayment payment) {
		super();
		this.ctx = ctx;
		InitForPayment(payment);
	}

	protected void InitForHrmintercheckoff(Mhrmintercheckoff hrmintercheckoff) {
		if (hrmintercheckoff != null) {
			setHrmintercheckoff(hrmintercheckoff);
			AD_Client_ID = getAD_Client_ID(ctx);
			AD_Org_ID = getAD_Org_ID(ctx);
			setBPAccountCode(getDefaultC_BP_BankAccount().getAccountNo());
			setC_BankAccount_ID(getOrgBankAccountID());
			
			
			setBPAccountCode(getDefaultC_BP_BankAccount().getAccountNo());
			setDateTrx(hrmintercheckoff.getDateFrom());
			setPayAmt(hrmintercheckoff.gethrm_total());
			setDescription(hrmintercheckoff.getName());
			//setC_BP_BankAccount_ID(getDefaultC_BP_BankAccount_ID());
			setC_BPartner_ID(getOrgBPartner_ID());
			setFI_PPC_ID(getDefaultFI_PPC_ID());
			setDocumentNo(hrmintercheckoff.getDocumentNo());
			setHrmintercheckofflist(hrmintercheckoff);
			//TODO
		}
	}

	protected void InitForHrmpayment(Mhrmpayment hrmpayment) {
		if (hrmpayment != null) {
			setM_hrmpayment(hrmpayment);
			AD_Client_ID = getAD_Client_ID(ctx);
			AD_Org_ID = getAD_Org_ID(ctx);
			setFI_ChiefSignature_ID(hrmpayment.getFI_ChiefSignature_ID());
			setFI_ChiefAccountantSignature_ID(hrmpayment
					.getFI_ChiefAccountantSignature_ID());
			setBPAccountCode(hrmpayment.getC_BP_BankAccount().getAccountNo());
			setDateTrx(hrmpayment.getDateFrom());
			setPayAmt(hrmpayment.gethrm_amountsalary());
			setDescription(hrmpayment.getName());
			setC_BankAccount_ID(hrmpayment.getC_BankAccount_ID());
			setC_BP_BankAccount_ID(hrmpayment.getC_BP_BankAccount_ID());
			setC_BPartner_ID(hrmpayment.getC_BPBank_ID());
			setFI_PPC_ID(hrmpayment.getFI_PPC_ID());
			setDocumentNo(hrmpayment.getDocumentNo());
			setHrmpaymentlist(hrmpayment);
		}
	}

	protected void setHrmpaymentlist(Mhrmpayment hrmpayment) {
		Mhrmpaymentlist[] hrmpaymentlist = hrmpayment.getLines();
		List<Item> _items = new ArrayList<MakeSwift.Item>();
		for (Mhrmpaymentlist Item : hrmpaymentlist) {
			_items.add(new Item(Item.getC_BPartner_ID(), getSalarySum(Item)));
		}
		setItems(_items);
	}

	protected void setHrmintercheckofflist(Mhrmintercheckoff hrmintercheckoff) {
		Mhrmintercheckoffline[] hrmintercheckofflist = hrmintercheckoff.getLinesIntercheckoff(false) ;
		List<Item> _items = new ArrayList<MakeSwift.Item>();
		for (Mhrmintercheckoffline Item : hrmintercheckofflist) {
			_items.add(new Item(Item.getC_BPartner_ID(), Item.gethrm_amount()));//TODO Правильно заполнить
		}
		setItems(_items);
	}

	protected BigDecimal getSalarySum(Mhrmpaymentlist item) {
		BigDecimal result = new BigDecimal(0);
		String sql = " select result from hrm_salarysum_v where hrm_payment_list_id = "
				+ item.gethrm_payment_list_ID();

		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = DB.prepareStatement(sql, null);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				result = rs.getBigDecimal("result");
			}
		} catch (SQLException e) {
			log.log(Level.WARNING, e.getLocalizedMessage());
		} finally {
			DB.close(rs, pstmt);
			rs = null;
			pstmt = null;
		}
		return result;
	}

	protected void InitForPayment(MPayment Payment) {
		if (Payment != null) {
			C_Payment_ID = Payment.getC_Payment_ID();
			if (C_Payment_ID > 0) {
				setPayment(Payment);
				AD_Client_ID = getAD_Client_ID(ctx);
				AD_Org_ID = getAD_Org_ID(ctx);
				setFI_ChiefSignature_ID(Payment.getFI_ChiefSignature_ID());
				setFI_ChiefAccountantSignature_ID(Payment
						.getFI_ChiefAccountantSignature_ID());
				setBPAccountCode(Payment.getC_BP_BankAccount().getAccountNo());
				setPaymentList(Payment);
				setDateTrx(Payment.getDateTrx());
				setPayAmt(Payment.getPayAmt());
				setDescription(Payment.getDescription());
				setC_BankAccount_ID(Payment.getC_BankAccount_ID());
				setC_BP_BankAccount_ID(Payment.getC_BP_BankAccount_ID());
				setC_BPartner_ID(Payment.getC_BPartner_ID());
				setFI_PPC_ID(Payment.getFI_PPC_ID());
				setDocumentNo(Payment.getDocumentNo());
			}
		}
	}

	protected int getAD_Client_ID(Properties ctx) {
		int result = -1;
		result = Integer
				.parseInt((ctx.getProperty("#AD_Client_ID") == null ? "-1"
						: ctx.getProperty("#AD_Client_ID")));
		return result;
	}

	protected int getAD_Org_ID(Properties ctx) {
		int result = -1;
		result = Integer.parseInt((ctx.getProperty("#AD_Org_ID") == null ? "-1"
				: ctx.getProperty("#AD_Org_ID")));
		return result;
	}

	protected int getOrgBPartner_ID() {
		int result = -1;
		MOrg org = new MOrg(ctx, AD_Org_ID, null);
		result = org.getLinkedC_BPartner_ID(null);
		return result;
	}

	public int make() {
		int result = 0;
		if (C_Payment_ID > 0) {
			String DocType = (payment != null ? payment.getC_DocType().getDocBaseType() : "");

			try {
				if (DocType.equals("APS") || DocType.equals("APA")){
					initStream();
					MainHead();
					AppHead();
					TextPart();
					Sign();
					doneStream();
				}
				else if(getC_Payment().getC_DocType().getName().equals("AP Payment (Salary)")) {
					initStream();
					MainHead();
					AppHead();
					TextPart();
					Sign();
					doneStream();
				} else if (getC_Payment().getC_DocType().getName()
						.equals("AP Payment")) {
					ErpsCreateSwift.createOldSwift(ctx);
				} else if (getC_Payment().getC_DocType().getName()
						.equals("AP Payment (OPV)")) {
					initStream();
					MainHead();
					AppHead();
					TextOPVPart();
					Sign();
					doneStream();
				} else {
					ADialog.info(25, null,
							"Нет правила для создания SWIFT файла");
				}
			} catch (Exception e) {
				log.log(Level.WARNING, "SWIFT:", e);
			}
		} else if (m_hrmpayment != null) {
			try {
				initStream();
				MainHead();
				AppHead();
				TextHRMPart();
				Sign();
				doneStream();
			} catch (Exception e) {
				log.log(Level.WARNING, "SWIFT:", e);
			}
		} else if (m_hrmintercheckoff != null) {
			try {
				initStream();
				MainHead();
				AppHead();
				TextHRMPart();
				Sign();
				doneStream();
			} catch (Exception e) {
				log.log(Level.WARNING, "SWIFT:", e);
			}
		} else {
			result = -1;
		}
		return result;
	}

	protected void MainHead() throws IOException {
		out.write("{" + cMainHead + ":" + mainHeadCode() + "}");
		out.write(endl);
	}

	protected void AppHead() throws IOException {
		out.write("{" + cAppHead + ":" + appHeadCode() + "}");
		out.write(endl);
	}

	protected void TextPart() throws IOException {
		if (getC_Payment() != null) {
			out.write("{" + cText + ":");
			out.write(endl);
			make20part();
			make50part();
			make52Bpart();
			make57Bpart();
			make59part();
			
			if(payment.getC_DocType().getDocBaseType().equals("APS"))
				makeAssign();	
			
			if (Items != null) {
				make70part();
				for (int i = 0; i < Items.size(); i++) {
					makePaymentItem(i, Items.get(i));
				}
			} else {

			}
			make32Apart();
			out.write("-}");
			out.write(endl);
		}
	}

	protected void TextOPVPart() throws IOException {
		if (C_Payment_ID > 0) {
			out.write("{" + cText + ":");
			out.write(endl);
			make20part();
			make50part();
			make52Bpart();
			make57Bpart();
			make59part();
			if (Items != null) {
				makeOPV70part();
				for (int i = 0; i < Items.size(); i++) {
					makeOPVPaymentItem(i, Items.get(i));
				}
			} else {

			}
			make32Apart();
			out.write("-}");
			out.write(endl);
		}
	}
	
	protected void TextHRMPart() throws IOException {
		if (m_hrmpayment != null || m_hrmintercheckoff != null) {
			out.write("{" + cText + ":");
			out.write(endl);
			make20part();
			make50part();
			make52Bpart();
			make57Bpart();
			make59part();
			make70part();
			if (Items != null) {
				for (int i = 0; i < Items.size(); i++) {
					makehrmpaymentitem(i, Items.get(i));
				}
			}
			make32Apart();
			out.write("-}");
			out.write(endl);
		}
	}

	protected void make20part() throws IOException {
		out.write(":20:" + "REFERENCE");
		out.write(endl); // Референс операции
	}

	protected void make50part() throws IOException {
		int orgBPartner_ID = getOrgBPartner_ID();
		out.write(":50:" + getAcctCode());
		out.write(endl);// Клиент инициатор
		out.write(getOrgNameCode());
		out.write(endl);
		out.write(getIDNCode(orgBPartner_ID));// out.write(getRNNCode(orgBPartner_ID)); 
		out.write(endl);
		out.write(getChiefCode());
		out.write(endl);
		out.write(getMainBKCode());
		out.write(endl);
		out.write(getIRSCode(orgBPartner_ID));
		out.write(endl);
		out.write(getSECOCode(orgBPartner_ID));
		out.write(endl);
	}

	protected void make52Bpart() throws IOException {
		out.write(":52B:" + getSwiftCode());
		out.write(endl); // Организация-инициатор
	}

	protected void make57Bpart() throws IOException {
		out.write(":57B:" + getBPSwiftCode());
		out.write(endl); // Организация-инициатор
	}

	protected void make59part() throws IOException {
		out.write(":59:" + getBPAccountCode());
		out.write(endl); // Бенефециар
		out.write(this.getNameCode(getC_BPartner_ID()));
		out.write(endl);
		out.write(getIDNCode(getC_BPartner_ID()));//out.write(getRNNCode(getC_BPartner_ID()));
		out.write(endl);
		out.write(getIRSCode(getC_BPartner_ID()));
		out.write(endl);
		out.write(getSECOCode(getC_BPartner_ID()));
		out.write(endl);
	}

	protected void makeAssign() throws IOException {
		out.write("/ASSIGN/" + (payment.getDescription() == null?"":payment.getDescription()));
		out.write(endl);
	}	
	
	protected void make70part() throws IOException {
		out.write(":70:");
		out.write(endl);
		out.write(getNumCode());
		out.write(endl);
		out.write(getDateCode());
		out.write(endl);
		out.write(getVOCode(""));
		out.write(endl);
		out.write(getSendCode());
		out.write(endl);
		out.write(getKNPCode());
		out.write(endl);
	}

	protected void makeOPV70part() throws IOException {
		out.write(":70:");
		out.write(endl);
		out.write(getNumCode());
		out.write(endl);
		out.write(getDateCode());
		out.write(endl);
		out.write(getVOCode(""));
		out.write(endl);
		out.write(getSendCode());
		out.write(endl);
		out.write(getKNPCode());
		out.write(endl);
		out.write(getPSOCode());
		out.write(endl);
		out.write(getPRTCode());
		out.write(endl);
		out.write(getPERIODCode());
		out.write(endl);
		out.write(getAssignCode());
		out.write(endl);
	}

	protected void makePaymentItem(int i, Item Item) throws IOException {
		if (getLA(Item.getC_BPartner_ID()).equals("")) {
			emptyLA.append(Item.getName() + "\n");
		} else {
			out.write(":21:" + Integer.toString(i + 1));
			out.write(endl);
			out.write(get32BCode(Item.getAmount()));
			out.write(endl);
			out.write(":70:");
			out.write(endl);
			out.write(getFMCode(Item.getName()));
			out.write(endl);
			out.write(getNMCode(Item.getName()));
			out.write(endl);
			out.write(getFTCode(Item.getName()));
			out.write(endl);
			out.write(getIDNCode(Item.getC_BPartner_ID()));//out.write(getRNNCode(Item.getC_BPartner_ID()));
			out.write(endl);
			out.write(getLACode(Item.getC_BPartner_ID()));
			out.write(endl);
		}
	}

	protected void makeOPVPaymentItem(int i, Item item) throws IOException {
		if (getLA(item.getC_BPartner_ID()).equals("")) {
			emptyLA.append(item.getName() + "\n");
		} else {
			out.write(":21:" + Integer.toString(i + 1));
			out.write(endl);
			out.write(get32BCode(item.getAmount()));
			out.write(endl);
			out.write(":70:");
			out.write(endl);
			out.write(getOPVCode(item));
			out.write(endl);
		}
	}

	protected void makehrmpaymentitem(int i, Item item) throws IOException {
		if (getLA(item.getC_BPartner_ID()).equals("")) {
			emptyLA.append(item.getName() + "\n");
		} else {
			out.write(":21:" + Integer.toString(i + 1));
			out.write(endl);
			out.write(get32BCode(item.getAmount()));
			out.write(endl);
			out.write(":70:");
			out.write(endl);
			out.write(getFMCode(item.getName()));
			out.write(endl);
			out.write(getNMCode(item.getName()));
			out.write(endl);
			out.write(getFTCode(item.getName()));
			out.write(endl);
			out.write(getIDNCode(item.getC_BPartner_ID()));//out.write(getRNNCode(item.getC_BPartner_ID()));
			out.write(endl);
			out.write(getLACode(item.getC_BPartner_ID()));
			out.write(endl);
		}
	}

	protected void make32Apart() throws IOException {
		BigDecimal sum = getSumPaymentLine();
		out.write(":32A:"
				+ get32A(getDateTrx(), (sum.doubleValue() == 0 ? getPayAmt()
						: sum)));
		out.write(endl);
	}

	protected String getOPVCode(Item item) {
		String result = "";
		Mhrmidcard idcard = Mhrmidcard.getHRM_Card(item.getC_BPartner_ID(),
				X_hrm_idcard.HRM_DOCTYPE_Sic, true);
		String backName = (idcard.getbackName() == null ? "" : idcard
				.getbackName());
		result += "/OPV/" + "S" + getSIK(item.getC_BPartner_ID()) + endl;
		result += "/"
				+ getFMCode(item.getName())
				+ (backName.equals("") ? "" : "/"
						+ getFM(backName).toUpperCase()) + endl;
		result += "/"
				+ getNMCode(item.getName())
				+ (backName.equals("") ? "" : "/"
						+ getNM(backName).toUpperCase()) + endl;
		result += "/"
				+ getFTCode(item.getName())
				+ (backName.equals("") ? "" : "/"
						+ getFT(backName).toUpperCase()) + endl;
		result += "/" + getDTCode(item.getC_BPartner_ID()) + endl;
		result += "/" + getIDNCode(item.getC_BPartner_ID());//getRNNCode(item.getC_BPartner_ID());
		return result;
	}

	protected String getDTCode(int C_BPartner_ID) {
		Timestamp date = null;
		X_HR_Employee empl = X_HR_Employee.getHR_Employee(C_BPartner_ID, true);
		date = empl.gethrm_dateOfBirth();
		String result = "/DT/" + getFullDate(date);
		return result;
	}

	protected String getFullDate(Timestamp date) {
		String YearAdd = Integer.toString(date.getYear() + 1900)
				.substring(0, 2);
		String result = YearAdd + getDate(date);
		return result;
	}

	protected String getSIK(int C_BPartner_ID) {
		String result = "";
		Mhrmidcard idcard = Mhrmidcard.getHRM_Card(C_BPartner_ID,
				X_hrm_idcard.HRM_DOCTYPE_Sic, true);
		result = idcard.gethrm_valuedoc();
		return result;
	}

	protected String get32A(Timestamp date, BigDecimal sum) {
		String result = getDate(date) + "KZT" + getFormatNum(sum);
		return result;
	}

	protected String getAssignCode() {
		String result = "/ASSIGN/" + getAssign();
		return result;
	}

	protected String getAssign() {
		String result = (getDescription() == null ? "" : getDescription());
		return result;
	}

	protected String getPSOCode() {
		String result = "/PSO/01";
		return result;
	}

	protected String getPRTCode() {
		String result = "/PRT/05";
		return result;
	}

	protected String getPERIODCode() {
		String result = "/PERIOD/" + getPERIOD(getDateTrx());
		return result;
	}

	protected String getLACode(int C_BPartner_ID) {
		String result = "/LA/" + getLA(C_BPartner_ID);
		return result;
	}

	protected String getLA(int C_BPartner_ID) {
		String result = "";
		int C_Bank_ID = getC_BP_BankAccount().getC_Bank_ID();
		int C_OrgBank_ID = getC_BankAccount().getC_Bank_ID();
		MBPBankAccount[] bankAccounts = MBPBankAccount.getOfBPartner(ctx,
				C_BPartner_ID);
		for (MBPBankAccount bankAcct : bankAccounts) {
			if ((bankAcct.getC_Bank_ID() == C_Bank_ID
					|| bankAcct.getC_Bank_ID() == C_OrgBank_ID || bankAccounts.length == 1)
					&& bankAcct.getBankAccountType().equals("C")) {
				result = bankAcct.getAccountNo();
				break;
			}
		}
		return result;
	}

	protected String getFMCode(String name) {
		String result = "/FM/" + getFM(name).toUpperCase();
		return result;
	}

	protected String getFM(String name) {
		String result = "";
		int i = name.indexOf(" ");
		if (i > 0) {
			result = name.substring(0, i);
		}
		return result;
	}

	protected String getNMCode(String name) {
		String result = "/NM/" + getNM(name).toUpperCase();
		return result;
	}

	protected String getNM(String name) {
		String result = "/";
		int i = name.indexOf(" ");
		if (i > 0) {
			int j = name.indexOf(" ", i + 1);
			if (j > 0) {
				result = name.substring(i + 1, j);
			}
		}
		return result;
	}

	protected String getFTCode(String name) {
		String result = "/FT/" + getFT(name).toUpperCase();
		return result;
	}

	protected String getFT(String name) {
		String result = "/";
		int i = name.indexOf(" ");
		if (i > 0) {
			int j = name.indexOf(" ", i + 1);
			if (j > 0) {
				result = name.substring(j + 1, name.length());
			}
		}
		return result;
	}

	protected String get32BCode(BigDecimal ammount) {
		String result = ":32B:KZT" + getFormatNum(ammount);
		return result;
	}

	protected String getKNPCode() {
		String result = "/KNP/" + getKNP();
		return result;
	}

	protected String getKNP() {
		String result = getFI_PPC().getFI_Code();
		return result;
	}

	protected String getSendCode() {
		String result = "/SEND/07"; // Ибо ваистину так!
		return result;
	}

	protected String getVOCode(String DocType_Name) {
		String result = "/VO/" + getVO(DocType_Name);
		return result;
	}

	protected String getVO(String DocType_Name) {
		String result = "01";
		if (DocType_Name.equals("AP Payment (Accountability)")) {
			result = "01";
		}
		return result;
	}

	protected String getDateCode() {
		String result = "";
		result = "/DATE/" + getDate(getDateTrx());
		return result;
	}

	protected String getDate(Timestamp d) {
		String result = "";
		String Year = Integer.toString(d.getYear() + 1900).substring(2, 4);
		String Month = (d.getMonth() + 1 < 10 ? "0" : "")
				+ Integer.toString(d.getMonth() + 1);
		String Day = (d.getDate() < 10 ? "0" : "")
				+ Integer.toString(d.getDate());
		result = Year + Month + Day;
		return result;
	}

	protected String getNumCode() {
		String result = "";
		result = "/NUM/" + getNum();
		return result;
	}

	protected String getNum() {
		String result = "";
		result = getDocumentNo();
		return result;
	}

	protected String getNameCode(int C_BPartner_ID) {
		String result = "";
		result = "/NAME/" + getName(C_BPartner_ID);
		return result;
	}

	protected String getName(int C_BPartner_ID) {
		String result = "";
		MBPartner bPartner = new MBPartner(ctx, C_BPartner_ID, null);
		if (bPartner != null) {
			result = bPartner.getName();
		}
		return result;
	}

	protected String getBPAccountCode() {
		String result = BPAccountCode;
		return result;
	}

	protected String getSECOCode(int C_BPartner_ID) {
		String result = "";
		result = "/SECO/" + getSECO(C_BPartner_ID);
		return result;
	}

	protected String getSECO(int C_BPartner_ID) {
		String result = "";
		if (getFI_Code(C_BPartner_ID).length() > 0) {
			result = getFI_Code(C_BPartner_ID).substring(1, 2);
		}
		return result;
	}

	protected String getIRSCode(int C_BPartner_ID) {
		String result = "";
		result = "/IRS/" + getIRS(C_BPartner_ID);
		return result;
	}

	protected String getIRS(int C_BPartner_ID) {
		String result = "";
		if (getFI_Code(C_BPartner_ID).length() > 0) {
			result = getFI_Code(C_BPartner_ID).substring(0, 1);
		}
		return result;
	}

	protected String getChiefCode() {
		String result = "";
		result = "/CHIEF/" + getChief();
		return result;
	}

	protected String getChief() {
		String result = "КУРГАНБЕКОВА З. Е.";
		if (getFI_ChiefSignature() != null) {
			MBPartner chief = getFI_ChiefSignature();
			result = convertName(chief.getName());
		}
		return result;
	}

	protected String getMainBKCode() {
		String result = "";
		result = "/MAINBK/" + getMainBK();
		return result;
	}

	protected String getMainBK() {
		String result = "НУРАХМЕТОВА А. Т.";
		if (getFI_ChiefAccountantSignature() != null) {
			MBPartner mainBK = getFI_ChiefAccountantSignature();
			result = convertName(mainBK.getName());
		}
		return result;
	}

	protected String getRNNCode(int C_BPartner_ID) {
		String result = "";
		result = "/RNN/" + getRNN(C_BPartner_ID);// getRNN(C_BPartner_ID)
		return result;
	}

	protected String getRNN(int C_BPartner_ID) {
		String result = "";
		MBPartner bPartner = new MBPartner(ctx, C_BPartner_ID, null);
		if (bPartner != null) {
			result = (bPartner.getFI_TIN() == null ? "" : bPartner.getFI_TIN());
		}
		return result;
	}
	
	protected String getIDNCode(int C_BPartner_ID) {
		String result = "";
		result = "/IDN/" + getIDN(C_BPartner_ID);
		return result;
	}

	protected String getIDN(int C_BPartner_ID) {
		String result = "";
		MBPartner bPartner = new MBPartner(ctx, C_BPartner_ID, null);
		if (bPartner != null) {
			result = (bPartner.getFI_BIN_IIN() == null ? "" : bPartner.getFI_BIN_IIN());
		}
		return result;
	}

	protected String getOrgNameCode() {
		String result = "";
		result = "/NAME/" + getOrgName();
		return result;
	}

	protected String getOrgName() {
		String result = "";
		MOrg org = new MOrg(ctx, AD_Org_ID, null);
		result = org.getName().toUpperCase();
		if (result == null) {
			result = "";
		}
		return result;
	}

	protected String mainHeadCode() {
		String result = "";
		result = "F01" + getSwiftCode() + "0000" + "0010" + "000001";
		return result;
	}

	protected String appHeadCode() {
		String result = "";
		result = "I" + "102" + "SGROSS" + "0000" + "U" + "3" + "003";
		return result;
	}

	protected String getAcctCode() {
		String result = "";
		result = "/D/" + getAccount(getOrgBankAccountID()); // /D - по дебету,
															// /C - по кредиту
		return result;
	}

	protected String getAccount(int C_BankAccount_ID) {
		String result = "";
		MBankAccount bankAccount = new MBankAccount(ctx, C_BankAccount_ID, null);
		result = bankAccount.getAccountNo();
		return result;
	}

	protected int getOrgBankAccountID() {
		int result = -1;
		int C_BankAccount_ID = getC_BankAccount_ID();
		result = C_BankAccount_ID;
		return result;
	}

	protected String getSwiftCode(int C_Bank_ID) {
		String result = "";
		MBank bank = new MBank(ctx, C_Bank_ID, null);
		if (bank != null) {
			result = bank.getSwiftCode();
		}
		return result;
	}

	protected String getSwiftCode() {
		String result = "";
		int C_Bank_ID = getC_BankAccount().getC_Bank_ID();
		result = getSwiftCode(C_Bank_ID);
		return result;
	}

	protected String getBPSwiftCode() {
		String result = "";
		int C_Bank_ID = getC_BP_BankAccount().getC_Bank_ID();
		result = getSwiftCode(C_Bank_ID);
		return result;
	}

	protected void Sign() throws IOException {

	}

	protected String getSWIFTFileName() {
		if (SWIFTFileName == null) {
			setSWIFTFileName(ChoiceDir() + "/Swift.txt"); // SWIFT по умолчанию
		}
		return SWIFTFileName;
	}

	public void setSWIFTFileName(String aSWIFTFileName) {
		if (SWIFTFileName != null) {

		}
		SWIFTFileName = new String(aSWIFTFileName);
	}

	protected int getC_Payment_ID(Properties ctx) {
		if (C_Payment_ID <= 0) {
			C_Payment_ID = Env.getContextAsInt(ctx, WindowNo, "C_Payment_ID");
		}
		return C_Payment_ID;
	}

	protected String ChoiceDir() {
		String result = "";
		final JFileChooser fc = new JFileChooser();
		JList list = new JList();
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
			result = fc.getSelectedFile().getAbsolutePath();
		}
		return result;
	}

	protected void initStream() throws FileNotFoundException, IOException {
		String FileName = getSWIFTFileName();
		File file = new File(FileName);// fc.getSelectedFile();
		fos = new FileOutputStream(file);
		out = new OutputStreamWriter(fos, "UTF8");// "CP866");
	}

	protected void doneStream() throws IOException {
		out.flush();
		out.close();
		fos.close();
		if (!emptyLA.toString().equals("")) {
			ADialog.info(25, null,
					"Ошибки при формировании SWIFT файла. Для просмотра нажмите OK");
		}
		String msg = "Cоздание SWIFT файла завершено.\n"
				+ (emptyLA.toString().equals("") ? "" : "Нет р/сч:\n"
						+ emptyLA.toString());
		ADialog.info(25, null, msg);
	}

	protected void errorStream() throws IOException {
		doneStream();
		File file = new File(getSWIFTFileName());
		file.delete();
	}

	protected String convertName(String name) {
		String result = "";
		String tmp = (name != null ? name : "");
		String family = "";
		String iN = "";
		String iO = "";
		int i = 0;
		if (tmp.length() > 0) {
			i = tmp.indexOf(" ", i);
			family = tmp.substring(0, i) + " ";
			tmp = name.substring(i + 1, tmp.length());
			if (tmp.length() > 0) {
				iN = tmp.substring(0, 1) + ". ";
				i = tmp.indexOf(" ");
				tmp = tmp.substring(i + 1, tmp.length());
				if (tmp.length() > 0) {
					iO = tmp.substring(0, 1) + ".";
				}
			}
		}
		result = family + iN + iO;
		result = result.toUpperCase();
		return result;
	}

	protected String getFI_Code(int C_BPartner_ID) {
		String result = "";
		MBPartner bPartner = new MBPartner(ctx, C_BPartner_ID, null);
		if (bPartner != null) {
			result = bPartner.getFI_CodeBeneficiary().getFI_Code();
		}
		return result;
	}

	protected BigDecimal getSumPaymentLine() {
		BigDecimal result = new BigDecimal(0);
		if (Items != null) {
			for (Item item : Items) {
				if (!getLA(item.getC_BPartner().getC_BPartner_ID()).equals("")) {
					result = result.add(item.getAmount());
				}
			}
		}
		return result;
	}

	protected String getFormatNum(BigDecimal n) {
		String result = String.format("%10.2f", n).trim();
		return result;
	}

	protected String getPERIOD(Timestamp date) {
		String result = "";
		String Year = Integer.toString((date.getYear() + 1900));
		int iMonth = date.getMonth();
		if (iMonth == 0) {
			iMonth = 12;
		}
		String Month = (iMonth < 10 ? "0" : "") + Integer.toString(iMonth);
		result = Month + Year;
		return result;
	}

	public int getFI_ChiefSignature_ID() {
		return FI_ChiefSignature_ID;
	}

	public void setFI_ChiefSignature_ID(int fI_ChiefSignature_ID) {
		FI_ChiefSignature_ID = fI_ChiefSignature_ID;
	}

	public MBPartner getFI_ChiefSignature() {
		MBPartner result = null;
		if (getFI_ChiefSignature_ID() > 0) {
			result = new MBPartner(ctx, getFI_ChiefSignature_ID(), null);
		}
		return result;
	}

	public int getFI_ChiefAccountantSignature_ID() {
		return FI_ChiefAccountantSignature_ID;
	}

	public void setFI_ChiefAccountantSignature_ID(
			int fI_ChiefAccountantSignature_ID) {
		FI_ChiefAccountantSignature_ID = fI_ChiefAccountantSignature_ID;
	}

	public MBPartner getFI_ChiefAccountantSignature() {
		MBPartner result = null;
		if (getFI_ChiefAccountantSignature_ID() > 0) {
			result = new MBPartner(ctx, getFI_ChiefAccountantSignature_ID(),
					null);
		}
		return result;
	}

	public int getFI_PPC_ID() {
		return FI_PPC_ID;
	}

	public void setFI_PPC_ID(int fI_PPC_ID) {
		FI_PPC_ID = fI_PPC_ID;
	}

	public X_FI_PPC getFI_PPC() {
		X_FI_PPC result = null;
		result = new X_FI_PPC(ctx, getFI_PPC_ID(), null);
		return result;
	}

	public Mhrmpayment getM_hrmpayment() {
		return m_hrmpayment;
	}

	public void setM_hrmpayment(Mhrmpayment m_hrmpayment) {
		this.m_hrmpayment = m_hrmpayment;
	}

	public void setBPAccountCode(String bPAccountCode) {
		BPAccountCode = bPAccountCode;
	}

	public int getC_BPartner_ID() {
		return C_BPartner_ID;
	}

	public void setC_BPartner_ID(int c_BPartner_ID) {
		C_BPartner_ID = c_BPartner_ID;
	}

	public MBPartner getC_BPartner() {
		MBPartner result = null;
		if (getC_BPartner_ID() > 0) {
			result = new MBPartner(ctx, getC_BPartner_ID(), null);
		}
		return result;
	}

	public String getDescription() {
		return Description;
	}

	public void setDescription(String description) {
		Description = description;
	}

	public int getC_BankAccount_ID() {
		return C_BankAccount_ID;
	}

	public void setC_BankAccount_ID(int c_BankAccount_ID) {
		C_BankAccount_ID = c_BankAccount_ID;
	}

	public MBankAccount getC_BankAccount() {
		MBankAccount result = new MBankAccount(ctx, getC_BankAccount_ID(), null);
		return result;
	}

	public int getC_BP_BankAccount_ID() {
		return C_BP_BankAccount_ID;
	}

	public void setC_BP_BankAccount_ID(int c_BP_BankAccount_ID) {
		C_BP_BankAccount_ID = c_BP_BankAccount_ID;
	}

	public MBPBankAccount getC_BP_BankAccount() {
		MBPBankAccount result = new MBPBankAccount(ctx,
				getC_BP_BankAccount_ID(), null);
		return result;
	}

	public BigDecimal getPayAmt() {
		return PayAmt;
	}

	public void setPayAmt(BigDecimal payAmt) {
		PayAmt = payAmt;
	}

	public String getDocumentNo() {
		return DocumentNo;
	}

	public void setDocumentNo(String documentNo) {
		if (documentNo != null) {
			DocumentNo = documentNo;
		}
	}

	public int getC_Payment_ID() {
		return C_Payment_ID;
	}

	public void setC_Payment_ID(int c_Payment_ID) {
		C_Payment_ID = c_Payment_ID;
	}

	public void setPayment(MPayment payment) {
		this.payment = payment;
	}

	public MPayment getC_Payment() {
		MPayment result = null;
		if (getC_Payment_ID() > 0) {
			if (payment == null) {
				payment = new MPayment(ctx, getC_Payment_ID(), null);
			}
			result = payment;
		}
		return result;
	}

	public List<Item> getItems() {
		return Items;
	}

	public void setItems(List<Item> items) {
		Items = items;
	}

	public void setPaymentList(MPayment payment) {
		List<MFI_C_PaymentLine> paymentLine = MFI_C_PaymentLine
				.getMFI_C_PaymentLines(log, ctx, getC_Payment_ID());
		List<Item> _items = new ArrayList<MakeSwift.Item>();
		for (MFI_C_PaymentLine paymentItem : paymentLine) {
			_items.add(new Item(paymentItem.getC_BPartner_ID(), paymentItem
					.getAmount()));
		}
		setItems(_items);
	}

	public Timestamp getDateTrx() {
		return DateTrx;
	}

	public void setDateTrx(Timestamp dateTrx) {
		DateTrx = dateTrx;
	}

	public Mhrmintercheckoff getHrmintercheckoff() {
		return m_hrmintercheckoff;
	}

	public void setHrmintercheckoff(Mhrmintercheckoff m_hrmintercheckoff) {
		this.m_hrmintercheckoff = m_hrmintercheckoff;
	}

	/*
	 * Класс для цикла по списку
	 * 
	 */

	protected class Item {
		private int C_BPartner_ID = -1;
		private BigDecimal Amount = null;
		private MBPartner m_BPartner = null;

		public MBPartner getM_BPartner() {
			return m_BPartner;
		}

		public void setM_BPartner(MBPartner m_BPartner) {
			this.m_BPartner = m_BPartner;
		}

		public Item(int _C_BPartner_ID, BigDecimal amount) {
			super();
			setC_BPartner_ID(_C_BPartner_ID);
			Amount = amount;
		}

		public int getC_BPartner_ID() {
			return C_BPartner_ID;
		}

		public void setC_BPartner_ID(int c_BPartner_ID) {
			C_BPartner_ID = c_BPartner_ID;
			setM_BPartner(new MBPartner(ctx,c_BPartner_ID,null));
		}

		public MBPartner getC_BPartner() {
			MBPartner result = getM_BPartner();
			if (result.getC_BPartner_ID() != C_BPartner_ID) {
				if (C_BPartner_ID > 0 ) {
					result = new MBPartner(ctx, C_BPartner_ID, null);
					setM_BPartner(result);
				}
			}
			return result;
		}

		public String getName() {
			String result = "";
			if (getC_BPartner() != null) {
				result = getC_BPartner().getName();
			}
			return result;
		}

		public BigDecimal getAmount() {
			return Amount;
		}

		public void setAmount(BigDecimal amount) {
			Amount = amount;
		}

	}
	
	// Куча костылей!!!
	protected MBankAccount getDefaultC_BP_BankAccount() {
		MBankAccount result = null;
		if (getDefaultC_BankAccount_ID() > 0) {
			result = new MBankAccount(ctx,getDefaultC_BankAccount_ID(),null); 
		}
		return result;
	}
	
	protected int getDefaultC_BankAccount_ID() {
		int result = 1000002; //TODO Это не правильно!
		//TODO
		return result;
	}
	
	protected int getDefaultC_BPBank_ID() {
		int result = 0;
		//TODO
		return result;
	}
	
	protected int getDefaultFI_PPC_ID() {
		int result = 1000107; 
		return result;//TODO Это не правильно!
	}
	
}
